package com.uama.image.ImagePreview;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeControllerBuilder;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.uama.image.ImageLoader;
import com.uama.image.R;
import com.uama.image.photeview.MultiTouchViewPager;
import com.uama.image.photeview.OnPhotoTapListener;
import com.uama.image.photeview.PhotoDraweeView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @author wenhu Tong
 * @email wenhu.tong@uama.com.cn
 * @date 2017/11/14 09:32
 * @desc
 */
public class ImagePreviewPopup extends PopupWindow {
    private List<String> mUrls;
    private Context mContext;
    private int mPosition = 0;
    private String mDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "uama";

    public ImagePreviewPopup(Context context, @NonNull List<String> urls) {
        this.mUrls = urls;
        this.mContext = context;
        init(context);
    }

    public ImagePreviewPopup(Context context, @NonNull List<String> urls, int position) {
        this.mUrls = urls;
        this.mContext = context;
        this.mPosition = position;
        init(context);
    }

    private void init(Context context) {
        View view = View.inflate(context, R.layout.popup_image_preview, null);
        setContentView(view);
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        setFocusable(true);
        setTouchable(true);
        setOutsideTouchable(true);
        setBackgroundDrawable(new BitmapDrawable(context.getResources(), (Bitmap) null));
        setAnimationStyle(R.style.PopupWindowAnimation);
        // 设置全屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                Field mLayoutInScreen = PopupWindow.class.getDeclaredField("mLayoutInScreen");
                mLayoutInScreen.setAccessible(true);
                mLayoutInScreen.set(this, true);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        initView(view);
    }

    private void initView(View view){
        MultiTouchViewPager viewPager = view.findViewById(R.id.view_pager);
        viewPager.setAdapter(new PreviewPaperAdapter(mUrls));
        viewPager.setCurrentItem(mPosition);
    }

    public void show(){
        showAtLocation(((Activity)mContext).getWindow().getDecorView(), 0, 0, 0);
    }

    public class PreviewPaperAdapter extends PagerAdapter {
        private List<String> mUrls;

        public PreviewPaperAdapter(List<String> urls) {
            this.mUrls = urls;
        }

        @Override
        public int getCount() {
            return mUrls.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup viewGroup, final int position) {
            Context context = viewGroup.getContext();
            View view = View.inflate(context, R.layout.layout_image_preview, null);
            initView(view, position);
            viewGroup.addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            return view;
        }

        private void initView(View view, int position) {
            TextView textView = view.findViewById(R.id.tv_photo_num);
            textView.setText(String.format("%d/%d", position + 1, mUrls.size()));
            final Uri uri = Uri.parse(mUrls.get(position));
            final PhotoDraweeView photoDraweeView = view.findViewById(R.id.pdv_photo);
            PipelineDraweeControllerBuilder controller = Fresco.newDraweeControllerBuilder();
            controller.setUri(uri);
            controller.setOldController(photoDraweeView.getController());
            controller.setControllerListener(new BaseControllerListener<ImageInfo>() {
                @Override
                public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                    super.onFinalImageSet(id, imageInfo, animatable);
                    if (imageInfo == null) {
                        return;
                    }
                    photoDraweeView.update(imageInfo.getWidth(), imageInfo.getHeight());
                }
            });
            photoDraweeView.setController(controller.build());
            photoDraweeView.setOnPhotoTapListener(new OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View view, float x, float y) {
                    ImagePreviewPopup.this.dismiss();
                }
            });

            final ImageView imageView = view.findViewById(R.id.img_download);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    File file = ImageLoader.getInstance().getCache(uri);
                    if (file == null) {
                        Toast.makeText(mContext, "本地图片，不用缓存", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    imageView.setVisibility(View.GONE);
                    try {
                        saveFile(file);
                        Toast.makeText(mContext, "文件保存到" + mDir, Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                }
            });
        }
    }

    private void saveFile(File file) throws IOException {
        String name = file.getName();
        name = name.substring(0, name.lastIndexOf(".")) + ".png";

        if (!new File(mDir).exists()){
            file.mkdirs();
        }

        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(new File(mDir, name));
        byte[] buffer = new byte[2048];
        int count;
        while ((count = fis.read(buffer)) != -1) {
            fos.write(buffer, 0, count);
        }
        fos.flush();
        fos.close();
        fis.close();
    }

}
